<template>
  <div class="app-container p-6">
    <!-- 页面标题和操作按钮 - 完全匹配原型 -->
    <div class="page-header-section flex flex-col md:flex-row md:items-center md:justify-between mb-6">
      <div class="page-title-area">
        <h1 class="text-2xl font-bold text-text-primary">权限管理</h1>
        <p class="text-text-muted mt-2">管理系统中的所有权限，包括接口权限、操作权限和资源权限</p>
      </div>
      <div class="page-actions-area mt-4 md:mt-0">
        <!-- 主要操作按钮 -->
        <button
          @click="handleAdd"
          v-permission="'permission:create'"
          class="primary-action-btn bg-primary hover:bg-primary-hover text-white px-6 py-2 rounded-md flex items-center shadow-card transition-all"
        >
          <i class="fas fa-plus mr-2"></i>
          <span>新增权限</span>
        </button>
      </div>
    </div>

    <!-- 搜索和筛选区域 - 完全匹配原型样式 -->
    <div class="search-form-card bg-panel rounded-lg shadow-card p-6 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <!-- 权限名称搜索 -->
        <div>
          <label class="block text-text-secondary mb-2 text-sm font-medium">权限名称</label>
          <div class="relative">
            <input
              type="text"
              v-model="queryParams.permissionName"
              placeholder="请输入权限名称"
              class="search-input pl-10 pr-4 py-2 w-full rounded-md border border-border bg-bg-hover focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
            >
            <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-muted"></i>
          </div>
        </div>

        <!-- 权限编码搜索 -->
        <div>
          <label class="block text-text-secondary mb-2 text-sm font-medium">权限编码</label>
          <div class="relative">
            <input
              type="text"
              v-model="queryParams.permissionCode"
              placeholder="请输入权限编码"
              class="search-input pl-10 pr-4 py-2 w-full rounded-md border border-border bg-bg-hover focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
            >
            <i class="fas fa-key absolute left-3 top-1/2 transform -translate-y-1/2 text-text-muted"></i>
          </div>
        </div>
        
        <!-- 关联菜单选择 -->
        <div>
          <label class="block text-text-secondary mb-2 text-sm font-medium">关联菜单</label>
          <div class="search-tree-select-wrapper">
            <el-tree-select
              v-model="queryParams.menuId"
              :data="menuTreeOptions"
              :props="{ label: 'menuTitle', value: 'id', children: 'children' }"
              placeholder="请选择关联菜单"
              clearable
              filterable
              :render-after-expand="false"
              class="search-tree-select w-full"
            />
          </div>
        </div>

      </div>

      <!-- 高级搜索和操作按钮 -->
      <div class="mt-4 flex justify-between items-center">
        <button class="text-primary hover:text-primary-hover text-sm transition-colors">
          <i class="fas fa-sliders-h mr-1"></i>
          高级搜索
        </button>

        <!-- 操作按钮组 -->
        <div class="flex space-x-3">
          <button
            @click="resetQuery"
            class="px-4 py-2 border border-border rounded-md text-text-secondary hover:bg-bg-hover transition-colors"
          >
            重置
          </button>
          <button
            @click="handleQuery"
            class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-hover shadow-sm transition-colors"
          >
            搜索
          </button>
        </div>
      </div>
    </div>

    <SystemTable
      title="权限列表"
      :total="total"
      @page-change="handlePageChange"
      @filter="handleTableFilter"
      @export="handleExport"
      export-permission="permission:export"
      v-loading="loading"
      :data="permissionList"
      row-key="permissionId"
      ref="tableRef"
    >
      <el-table-column prop="permissionCode" label="权限代码" show-overflow-tooltip align="left" />
      <el-table-column prop="permissionName" label="权限名称" show-overflow-tooltip align="left" />
      <el-table-column label="关联菜单" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.menuName" type="info" size="small">
            {{ row.menuName }}
          </el-tag>
          <span v-else style="color: var(--text-muted);">未关联</span>
        </template>
      </el-table-column>
      <el-table-column label="权限类型" width="100" align="center">
        <template #default="{ row }">
          <span
            class="status-tag"
            :class="{
              'status-enabled': row.permissionType === 'API',
              'status-pending': row.permissionType === 'OP',
              'status-disabled': row.permissionType === 'RESOURCE'
            }"
          >
            {{ getPermissionTypeText(row.permissionType) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="权限描述" show-overflow-tooltip align="left" />
      <el-table-column label="状态" width="80" align="center">
        <template #default="{ row }">
          <span
            class="status-tag"
            :class="row.status === 1 ? 'status-enabled' : 'status-disabled'"
          >
            {{ row.status === 1 ? '启用' : '禁用' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" sortable show-overflow-tooltip align="left" />
      <el-table-column label="操作" fixed="right" align="center">
        <template #default="{ row }">
          <div class="table-actions">
            <button
              class="action-btn edit-btn"
              @click="handleEdit(row)"
              v-permission="'permission:update'"
              title="编辑"
            >
              <i class="fas fa-edit"></i>
            </button>
            <button
              class="action-btn delete-btn"
              @click="handleDelete(row)"
              v-permission="'permission:delete'"
              title="删除"
            >
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </template>
      </el-table-column>
    </SystemTable>
  </div>

  <!-- 新增/编辑权限对话框 -->
  <el-dialog
    v-model="formVisible"
    :title="isEdit ? '编辑权限' : '新增权限'"
    width="600px"
    destroy-on-close
  >
    <el-form
      ref="permissionFormRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="权限编码" prop="permissionCode">
        <el-input
          v-model="formData.permissionCode"
          placeholder="请输入权限编码"
          :disabled="isEdit"
        />
      </el-form-item>

      <el-form-item label="权限名称" prop="permissionName">
        <el-input
          v-model="formData.permissionName"
          placeholder="请输入权限名称"
        />
      </el-form-item>

      <el-form-item label="权限类型" prop="permissionType">
        <el-select v-model="formData.permissionType" placeholder="请选择权限类型">
          <el-option label="接口权限" value="API" />
          <el-option label="操作权限" value="OP" />
          <el-option label="资源权限" value="RESOURCE" />
        </el-select>
      </el-form-item>

      <el-form-item label="关联菜单" prop="menuId">
        <el-tree-select
          v-model="formData.menuId"
          :data="menuTreeOptions"
          :props="{ label: 'menuTitle', value: 'id', children: 'children' }"
          placeholder="请选择关联菜单（可选）"
          clearable
          filterable
          :render-after-expand="false"
        />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入权限描述"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElSelect, ElOption } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { permissionApi } from '@/api/permission'
import { menuApi } from '@/api/menu'
import type { PermissionDTO, MenuDTO } from '@/types/api'
import SystemTable from '@/components/SystemTable/index.vue'

// 响应式数据
const loading = ref(false)
const permissionList = ref<PermissionDTO[]>([])
const total = ref(0)

// 菜单相关数据
type MenuTreeNode = MenuDTO & { id: string; menuTitle: string; children?: MenuTreeNode[] }
const menuTreeOptions = ref<MenuTreeNode[]>([])
const menuMap = ref<Map<string, MenuDTO>>(new Map())

// 表单相关
const formVisible = ref(false)
const isEdit = ref(false)
const permissionFormRef = ref<any>()

// 表单数据
const formData = reactive({
  id: '',
  permissionCode: '',
  permissionName: '',
  description: '',
  permissionType: 'API',
  menuId: '',
  status: 1
})

const queryParams = reactive({
  current: 1,
  size: 10,
  permissionName: '',
  permissionCode: '',
  permissionType: '',
  menuId: '',
  status: undefined as number | undefined
})

// 方法
// 获取菜单树数据 - 直接使用后端字段
const getMenuTree = async () => {
  try {
    const response = await menuApi.getMenuTree()
    // 直接使用后端返回的数据
    menuTreeOptions.value = processMenuTree(response.data || [])

    // 构建菜单映射 - 使用后端的 id 字段
    const buildMenuMap = (menus: MenuDTO[]) => {
      menus.forEach(menu => {
        const id = (menu as any).id
        if (id) {
          menuMap.value.set(id, menu)
        }
        // 递归处理子菜单 - 后端使用 children 字段
        if (menu.children && menu.children.length > 0) {
          buildMenuMap(menu.children)
        }
      })
    }
    buildMenuMap(response.data || [])
    
    // 调试日志
    if (import.meta.env.MODE === 'development') {
      console.log('菜单映射构建完成，共', menuMap.value.size, '个菜单')
    }
  } catch (error) {
    console.error('获取菜单树失败:', error)
  }
}

// 处理菜单树数据 - 直接使用后端字段
const processMenuTree = (menus: MenuDTO[]): MenuTreeNode[] => {
  return menus.map<MenuTreeNode>(menu => ({
    ...(menu as MenuDTO),
    id: (menu as any).id as string,
    menuTitle: (menu.title || (menu as any).name) as string,
    // 后端使用 children 字段
    children: menu.children ? processMenuTree(menu.children) : []
  }))
}

const getList = async () => {
  loading.value = true
  try {
    const response = await permissionApi.queryPermissions(queryParams)
    // 为权限数据添加菜单名称 - 使用后端的 title 字段
    const permissions = (response.data.records || []).map((permission: PermissionDTO) => {
      let menuName = ''
      if (permission.menuId) {
        const menu = menuMap.value.get(permission.menuId)
        if (menu) {
          // 使用后端的 title 字段
          menuName = menu.title || (menu as any).name || '未知菜单'
        } else {
          menuName = '未知菜单'
        }
      }
      
      return {
        ...permission,
        menuName
      }
    })
    permissionList.value = permissions
    total.value = response.data.total
    
    // 调试日志
    if (import.meta.env.MODE === 'development') {
      console.log('权限列表加载完成，共', permissions.length, '条数据')
      const hasMenu = permissions.filter(p => p.menuName && p.menuName !== '未知菜单')
      console.log('其中', hasMenu.length, '条有关联菜单')
    }
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

const getPermissionTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'API': '接口权限',
    'OP': '操作权限',
    'RESOURCE': '资源权限'
  }
  return typeMap[type] || type
}

const getPermissionTypeTag = (type: string): 'success' | 'warning' | 'primary' | 'info' | 'danger' => {
  const tagMap: Record<string, 'success' | 'warning' | 'primary' | 'info' | 'danger'> = {
    'API': 'success',
    'OP': 'warning',
    'RESOURCE': 'primary'
  }
  return tagMap[type] || 'info'
}

const handleQuery = () => {
  queryParams.current = 1
  getList()
}

const resetQuery = () => {
  queryParams.permissionName = ''
  queryParams.permissionCode = ''
  queryParams.permissionType = ''
  queryParams.menuId = ''
  queryParams.status = undefined
  queryParams.current = 1
  getList()
}

// SystemTable 事件处理
const handlePageChange = (page: number, pageSize: number) => {
  queryParams.current = page
  queryParams.size = pageSize
  getList()
}

const handleTableFilter = () => {
  // 表格筛选逻辑
  console.log('表格筛选')
}

const handleExport = () => {
  // 导出逻辑
  ElMessage.success('导出功能开发中...')
}

const handleAdd = () => {
  formVisible.value = true
  isEdit.value = false
  nextTick(() => {
    if (permissionFormRef.value) {
      permissionFormRef.value.resetFields()
    }
  })
  // 重置表单数据
  Object.assign(formData, {
    permissionCode: '',
    permissionName: '',
    description: '',
    permissionType: 'API',
    menuId: '',
    status: 1
  })
}

const handleEdit = (row: PermissionDTO) => {
  formVisible.value = true
  isEdit.value = true
  nextTick(() => {
    if (permissionFormRef.value) {
      permissionFormRef.value.resetFields()
    }
  })
  // 填充表单数据
  Object.assign(formData, {
    id: row.permissionId,
    permissionCode: row.permissionCode,
    permissionName: row.permissionName,
    description: row.description || '',
    permissionType: row.permissionType || row.type || 'API',
    menuId: row.menuId || '',
    status: row.status
  })
}

const handleDelete = async (row: PermissionDTO) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限"${row.permissionName}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await permissionApi.deletePermission(row.permissionId!)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 表单提交
const handleSubmit = async () => {
  try {
    if (!permissionFormRef.value) return
    await permissionFormRef.value.validate()

    loading.value = true

    if (isEdit.value) {
      // 编辑权限
      await permissionApi.updatePermission(formData.id, formData)
      ElMessage.success('权限更新成功')
    } else {
      // 新增权限
      await permissionApi.createPermission(formData)
      ElMessage.success('权限创建成功')
    }

    formVisible.value = false
    getList()
  } catch (error: any) {
    console.error('保存权限失败:', error)
    ElMessage.error(error?.message || '保存失败')
  } finally {
    loading.value = false
  }
}

// 表单取消
const handleCancel = () => {
  formVisible.value = false
  if (permissionFormRef.value) {
    permissionFormRef.value.resetFields()
  }
}

// 表单验证规则
const formRules = {
  permissionCode: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { min: 2, max: 50, message: '权限编码长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  permissionType: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ]
}

// 生命周期
onMounted(async () => {
  await getMenuTree()  // 先加载菜单数据
  getList()           // 再加载权限数据
})
</script>

